import api from '@/store/api';

export const useConfigureStore = defineStore('configure', () => {
  const sensorInfo = ref([] as any[]);

  const setInfo = (info: { [index: string]: any }) => {
    sensorInfo.value = info.Sensor;
  };

  const download = async () => {
    return await api
      .get('/oem/v1/Configs/Configuration', {
        responseType: 'blob',
      })
      .then((res: any) => {
        const filename = res.headers['content-disposition']
          .split('filename=')[1]
          .replace(/"/g, '');
        const URL = window.URL.createObjectURL(res.data);

        const link = document.createElement('a');
        link.href = URL;
        link.download = filename;
        link.click();
        window.URL.revokeObjectURL(URL);
      })
      .catch((err) => {
        throw err;
      });
  };

  const getConfigures = async () => {
    const promises: Promise<void>[] = [];
    const info: { [index: string]: any } = {};
    const configureUrls: { [index: string]: string } = {
      Sensors: '/oem/v1/Sensors/Thresholds',
    };
    for (const option in configureUrls) {
      const promise = api.get(configureUrls[option]).then(({ data }) => {
        info.Sensor = data[option];
      });
      promises.push(promise);
    }
    await api
      .all(promises)
      .then(() => {
        setInfo(info);
      })
      .catch((error) => {
        console.log(error);
      });
  };

  const UpdateSensorConfigure = async (diffList: {
    items: { [index: string]: any }[];
  }) => {
    await api
      .patch('/oem/v1/Sensors/Thresholds', diffList)
      .catch((error) => {
        throw error;
      })
      .finally(() => {
        getConfigures();
      });
  };
  const upload = async (file: File) => {
    return await api
      .post('/oem/v1/Configs/Configuration', file, {
        headers: { 'Content-Type': 'application/octet-stream' },
      })
      .catch((err) => {
        console.log(err.response);
        throw err.response;
      });
  };
  return {
    sensorInfo,
    setInfo,
    download,
    getConfigures,
    UpdateSensorConfigure,
    upload,
  };
});
